/**
 * 从备份文件恢复数据库
 * 将SQL备份文件导入到指定的数据库
 */

const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 数据库配置
const TARGET_DB = {
  host: '43.143.253.188',
  port: 3306,
  user: 'nextjs',
  password: 'yEAiRE2jcxTyRBy5',
  database: 'nextjs_backup',  // 目标数据库
  charset: 'utf8mb4'
};

class DatabaseRestore {
  constructor() {
    this.connection = null;
  }

  async connect() {
    try {
      console.log('🔄 连接目标数据库...');
      this.connection = await mysql.createConnection(TARGET_DB);
      await this.connection.execute("SET NAMES utf8mb4");
      await this.connection.execute("SET time_zone = '+08:00'");
      console.log('✅ 目标数据库连接成功');
    } catch (error) {
      console.error('❌ 数据库连接失败:', error.message);
      
      if (error.code === 'ER_BAD_DB_ERROR') {
        console.error('💡 目标数据库不存在，请先创建：');
        console.error(`   CREATE DATABASE ${TARGET_DB.database} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;`);
      }
      
      throw error;
    }
  }

  async disconnect() {
    if (this.connection) {
      await this.connection.end();
      console.log('✅ 数据库连接已关闭');
    }
  }

  async restoreFromFile(filePath) {
    try {
      console.log(`🔄 从文件恢复: ${filePath}`);
      
      if (!fs.existsSync(filePath)) {
        console.error(`❌ 文件不存在: ${filePath}`);
        return { success: false, error: '文件不存在' };
      }

      const sqlContent = fs.readFileSync(filePath, 'utf8');
      const statements = sqlContent.split(';').filter(stmt => stmt.trim());
      
      let successCount = 0;
      let errorCount = 0;
      
      for (const statement of statements) {
        const trimmedStmt = statement.trim();
        if (trimmedStmt) {
          try {
            await this.connection.execute(trimmedStmt);
            successCount++;
          } catch (error) {
            console.error(`❌ 执行SQL失败: ${error.message}`);
            console.error(`   SQL: ${trimmedStmt.substring(0, 100)}...`);
            errorCount++;
          }
        }
      }
      
      console.log(`✅ 文件恢复完成: 成功${successCount}条，失败${errorCount}条`);
      return { success: true, successCount, errorCount };
      
    } catch (error) {
      console.error(`❌ 恢复文件失败:`, error.message);
      return { success: false, error: error.message };
    }
  }

  async restoreAllBackups() {
    try {
      const backupDir = path.join(__dirname, 'backup');
      
      if (!fs.existsSync(backupDir)) {
        console.error('❌ 备份目录不存在');
        return;
      }

      const files = fs.readdirSync(backupDir)
        .filter(file => file.endsWith('.sql'))
        .sort();

      console.log(`🔄 发现 ${files.length} 个备份文件`);

      const results = {
        total: files.length,
        success: 0,
        failed: 0,
        details: []
      };

      for (const file of files) {
        const filePath = path.join(backupDir, file);
        const result = await this.restoreFromFile(filePath);
        
        if (result.success) {
          results.success++;
          results.details.push({
            file,
            status: 'success',
            successCount: result.successCount,
            errorCount: result.errorCount
          });
        } else {
          results.failed++;
          results.details.push({
            file,
            status: 'failed',
            error: result.error
          });
        }
        
        console.log(''); // 空行分隔
      }

      return results;

    } catch (error) {
      console.error('❌ 恢复所有备份失败:', error.message);
      throw error;
    }
  }

  printSummary(results) {
    console.log('\n📊 恢复总结:');
    console.log(`  总文件数: ${results.total}`);
    console.log(`  成功: ${results.success}`);
    console.log(`  失败: ${results.failed}`);
    console.log(`  成功率: ${Math.round((results.success / results.total) * 100)}%`);

    if (results.failed > 0) {
      console.log('\n❌ 失败的文件:');
      results.details
        .filter(detail => detail.status === 'failed')
        .forEach(detail => {
          console.log(`  - ${detail.file}: ${detail.error}`);
        });
    }
  }
}

// 主函数
async function main() {
  const restore = new DatabaseRestore();
  
  try {
    // 连接数据库
    await restore.connect();
    
    // 恢复所有备份
    const results = await restore.restoreAllBackups();
    restore.printSummary(results);
    
    console.log('\n🎉 数据库恢复完成！');
    
  } catch (error) {
    console.error('❌ 恢复失败:', error);
    process.exit(1);
  } finally {
    await restore.disconnect();
  }
}

// 处理程序退出
process.on('SIGINT', async () => {
  console.log('\n🛑 恢复被中断');
  process.exit(0);
});

// 运行主函数
if (require.main === module) {
  main();
}

module.exports = DatabaseRestore;
